/**
 * 
 */
package com.kylin.frame.core.interceptor;

import net.sf.json.JSONObject;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.kylin.frame.core.activerecord.DbModel;
import com.kylin.frame.util.ContantsUtil;
import com.kylin.frame.util.WebUtils;
import com.kylin.frame.web.SessionMember;

/**
 * 权限拦截器，用来校验当前用户是否有权限
 * 
 * @author huxiang
 * 
 */
public class AuthInterceptor implements Interceptor {

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.jfinal.aop.Interceptor#intercept(com.jfinal.core.ActionInvocation)
	 */
	@Override
	public void intercept(ActionInvocation ai) {

		Controller c = ai.getController();
		SessionMember sm = (SessionMember) WebUtils.getSessionAttribute(
				c.getRequest(), ContantsUtil._SESSIONOB);
		
		if (null == sm) {// 没有登录
			
			// 如果是ajax请求
			if (WebUtils.isAjaxRequest(c.getRequest())) {
				JSONObject ob = new JSONObject();
				ob.put("_resCode", "当前用户没有登录，请登录");
				ob.put("doit", "function(){window.location.href='"
						+ c.getRequest().getContextPath() + "/login" + "'}");
				c.renderJson(ob.toString());
				return;
			} else {
				c.redirect(c.getRequest().getContextPath() + "/login");
				return;
			}
		} else {
			DbModel.setSessionOb(sm);
			ai.invoke();
		}

	}

}
